package cn.flying.base.security.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import java.util.Date;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.security.configuration.LoginUser;
import cn.flying.base.security.domain.SysLoginLog;
import cn.flying.base.security.service.SysUserService;

/**
 * @description: httpSession 监听实现类  监听器注册可以用过注解@WebListener，也可以通过ServletListenerRegistrationBean注入，
 * @author: lvyong
 * @date: 2023年06月05日 19:10
 * @version: 1.0
 */
@WebListener
public class CustomHttpSessionListener implements HttpSessionListener {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String id = session.getId();
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        logger.info("session销毁了");
        HttpSession session = event.getSession();
        SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext == null) {
            return;
        }
        LoginUser loginUser = (LoginUser) securityContext.getAuthentication().getPrincipal();
        if (loginUser == null) {
            return;
        }
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
        SysUserService sysUserService = (SysUserService) context.getBean("sysUserService");
        if (sysUserService == null) {
            return;
        }
        //这里要处理一下，主动退出spring security和session destroyed都会调用这里，所有要去重

        try {
            //保存登录日志
            SysLoginLog loginLog = new SysLoginLog();
            loginLog.setUserId(loginUser.getUserId());
            loginLog.setUserName(loginUser.getUsername());
            loginLog.setName(loginUser.getName());
            //I 登入成功 O 登出成功  F 登入失败  T 会话失效
            loginLog.setHappenType("T");
            loginLog.setHappenTime(new Date());
            loginLog.setRemark("会话过期失效");
            loginLog.setTenantId(loginUser.getTenantId());
            loginLog.setCreatedBy(loginUser.getUsername());
            loginLog.setCreatedTime(new Date());
            loginLog.setUpdatedBy(loginUser.getUsername());
            loginLog.setUpdatedTime(new Date());
            loginLog.setRevision(0L);
            sysUserService.insertLoginLog(loginLog);
            System.out.println("失效日志");
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }
    }
}
